<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{'min-height': mainHeight+'px'}">
                <div class="panel-body">
                    <div class="btn-group" style="margin-bottom: 15px">
                        <el-button @click="create" type="primary" icon="fa fa-plus"
                                   size="small"> 新增
                        </el-button>
                        <el-button @click="list" type="primary" icon="fa fa-refresh"
                                   size="small"> 刷新
                        </el-button>
                    </div>
                    <el-table  v-loading="loading"
                               element-loading-text="努力加载中..."
                               element-loading-spinner="el-icon-loading"
                               :data="tableData" :border="true" style="width: 100%">
                        <el-table-column prop="id" label="编号" width="80px"></el-table-column>
                        <el-table-column prop="thumb" label="头像" width="120px">
                            <template slot-scope="scope">
                                <img :src="scope.row.thumb" style="height: 85px;width: 85px;border-radius: 50%"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="名称" width="200px"></el-table-column>
                        <el-table-column prop="created_at" label="时间" width="200px">
                            <template slot-scope="scope">{{ scope.row.created_at ? moment(scope.row.created_at).format('YYYY-MM-DD HH:mm') : ''}}</template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>
                                    编辑</el-button>
                                <el-button icon="fa fa-trash"
                                           @click="destory(scope.row)" type="danger" size="mini" plain> 删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <div class="pagination-total">共 <em>{{pageData.total}}</em> 个分类</div>
                        <el-pagination  v-if="!loading && pageData && pageData.last_page > 1" background layout="prev, pager, next, jumper"
                                        :page-size="pageData.per_page"
                                        :total="pageData.total" :current-page="pageData.current_page"
                                        @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </div>
            </section>
        </el-main>
        <!-- 编辑用户，不用创建用户 -->
        <el-dialog
            :title="dialogTitle"
            custom-class="bh-dialog"
            top="23vh"
            @open="resetForm('formData')"
            :visible.sync="updateDialog"
            width="500px">
            <el-form :model="formData" :rules="rules" ref="formData" label-width="80px" class="demo-ruleForm">
                <el-form-item required label="名称：" prop="name">
                    <el-input v-model="formData.name" placeholder="请填写分类名称"></el-input>
                </el-form-item>
                <el-form-item required label="头像：" prop="thumb">
                    <el-upload
                        class="avatar-uploader"
                        :action="upload"
                        :show-file-list="false"
                        :headers="myHeaders"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload" name="pic">
                        <img v-if="formData.thumb" :src="formData.thumb" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateDialog = false">取 消</el-button>
                <el-button type="primary" @click="update('formData')">确 定</el-button>
              </span>
        </el-dialog>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {CategoryList,CategoryUpdate,CategoryDestory} from '../../utils/axios';
    export default {
        components:{vBreadcrumb},
        data(){
            return {
                breadcumb:[{name: "分类管理"},],
                tableData:[],//列表数据
                pageData:[],//分页数据
                updateDialog: false,
                search: {page:null},//筛选
                dialogTitle: '',
                //用户表单
                formData:{
                    id:0,
                    name:'',
                    thumb:'',
                },
                rules: {
                    name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }],
                    thumb: [{ required: true, message: '请添加分类头像', trigger: 'change' }],
                },
            }
        },
        activated(){
            this.$store.dispatch('setActive', '/category');
            this.list();
        },
        computed: {
            ...mapGetters(['active','mainHeight','loading','upload']),
            myHeaders() {
                var token = this.$storage.get('token');
                return {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            },
        },
        methods:{
            //回调1
            handleAvatarSuccess(res, file) {
                if (res.code) {
                    this.$message.error(res.msg);
                } else {
                    this.formData.thumb = res.data;
                }
            },
            //回调2
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //分页
            handleCurrentChange(val) {
                this.search.page = val;
                this.list();
            },
            //获取列表
            list(){
                this.$store.dispatch('setLoading', true);
                CategoryList({params: this.search}).then((response)=>{
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.tableData = response.data.data;
                        this.pageData = response.data;
                    }
                })
            },
            //编辑
            create(){
                this.formData = {
                    id:0,
                    name:'',
                    thumb:'',

                },
                this.updateDialog = true;
                this.dialogTitle = '新增分类';
            },
            //编辑
            edit(info){
                this.formData = {
                    id:info.id,
                    name: info.name,
                    thumb:info.thumb,

                }
                this.updateDialog = true;
                this.dialogTitle = '编辑分类';
            },
            //更新
            update(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        CategoryUpdate(this.formData).then((response)=>{
                            if(response.code){
                                this.$message.error(response.msg);
                            }else{
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose:() =>{
                                        this.updateDialog = false;
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //删除
            destory(info){
                this.$confirm('确定要删除"'+info.name+'"用户信息吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    CategoryDestory({params:{id: info.id}}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {});
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName]!==undefined) {
                    this.$refs[formName].resetFields();
                }
            },
        },
    }
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        border-radius: 50%;
        /*position: relative;*/
        /*left: 50%;*/
        /*margin-left: -89px;*/
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
